<template>
  <div class="p-6 max-w-xl mx-auto">
    <h2 class="text-2xl font-bold mb-4">创建知识点</h2>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.prevent="handleSubmit"
    >
      <el-form-item :error="nameError" :required="true" label="名称" prop="name">
        <el-input
          v-model="form.name"
          clearable
          placeholder="请输入知识点名称"
          @input="nameError = ''"
        />
      </el-form-item>

      <el-form-item :required="true" label="所属学科" prop="subject">
        <el-select v-model="form.subject" clearable placeholder="请选择学科">
          <el-option label="语文" value="语文" />
          <el-option label="数学" value="数学" />
          <el-option label="英语" value="英语" />
          <el-option label="物理" value="物理" />
          <el-option label="化学" value="化学" />
          <el-option label="生物" value="生物" />
          <el-option label="政治" value="政治" />
          <el-option label="历史" value="历史" />
          <el-option label="地理" value="地理" />
        </el-select>
      </el-form-item>

      <el-form-item label="描述">
        <el-input
          v-model="form.description"
          :rows="4"
          clearable
          placeholder="可选描述"
          type="textarea"
        />
      </el-form-item>

      <el-form-item>
        <el-button :loading="loading" type="primary" @click="handleSubmit"> 提交 </el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { apiClient } from '@/api'

interface KnowledgePointRequest {
  name: string
  subject: string
  description?: string
  parentId?: number | null
}

const form = ref<KnowledgePointRequest>({
  name: '',
  subject: '',
  description: '',
})

const formRef = ref<FormInstance>()

const loading = ref(false)

const nameError = ref('')

const rules = {
  name: [
    { required: true, message: '名称不能为空', trigger: 'blur' },
    { min: 2, message: '名称长度不能少于2个字符', trigger: 'blur' },
  ],
  subject: [{ required: true, message: '请选择学科', trigger: 'change' }],
}

const handleSubmit = () => {
  nameError.value = ''

  formRef.value?.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写正确的表单信息')
      return
    }
    loading.value = true
    try {
      await apiClient.post('/admin/create-knowledge-points', form.value)
      ElMessage.success('创建成功')
      resetForm()
      formRef.value?.resetFields()
    } catch (error: any) {
      const msg = error?.response?.data?.message || error?.response?.data || '创建失败'
      ElMessage.error(msg)
    } finally {
      loading.value = false
    }
  })
}

const resetForm = () => {
  form.value = {
    name: '',
    subject: '',
    description: '',
  }
  nameError.value = ''
  formRef.value?.clearValidate()
}
</script>
